package com.thinkit.bigdata.web.service.impl.sys;

import com.google.common.base.Strings;
import com.thinkit.bigdata.web.dao.sys.SysApprovalConfigMapper;
import com.thinkit.bigdata.web.dao.sys.SysApprovalConfigRelMapper;
import com.thinkit.bigdata.web.model.BaseEntity;
import com.thinkit.bigdata.web.model.result.Constants;
import com.thinkit.bigdata.web.model.result.HtmlResult;
import com.thinkit.bigdata.web.model.sec.User;
import com.thinkit.bigdata.web.model.sys.*;
import com.thinkit.bigdata.web.service.sys.SysApprovalConfigService;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.converters.DateConverter;
import org.apache.shiro.SecurityUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.InvocationTargetException;
import java.util.*;

@Service
public class SysApprovalConfigServiceImpl implements SysApprovalConfigService {

    @Resource
    private SysApprovalConfigMapper configMapper;

    @Resource
    private SysApprovalConfigRelMapper relMapper;

    public List<SysApprovalConfigRel> selectByCodeAndLine(String code, Long lineNumber) {
        SysApprovalConfigExample example = new SysApprovalConfigExample();
        example.createCriteria().andDatacodeEqualTo(code).andLinenumberEqualTo(lineNumber);
        example.setOrderByClause("inputTime desc");
        List<SysApprovalConfig> configs = configMapper.selectByExample(example);
        if (configs.isEmpty()) {//查询提交角色为空的记录
            SysApprovalConfigExample exampleNull = new SysApprovalConfigExample();
            exampleNull.createCriteria().andDatacodeEqualTo(code).andLinenumberIsNull();
            exampleNull.setOrderByClause("inputTime desc");
            configs = configMapper.selectByExample(exampleNull);
            if (configs.isEmpty()) {//还是没有记录，那就是没有记录了
                return new ArrayList<>();
            }
        }
        SysApprovalConfigRelExample relExample = new SysApprovalConfigRelExample();
        relExample.createCriteria().andAppconfigidEqualTo(configs.get(0).getId());
        relExample.setOrderByClause("number asc");
        return relMapper.selectByExample(relExample);
    }

    @Override
    public HtmlResult deleteByExample(SysApprovalConfigExample example) {
        return null;
    }

    @Override
    public HtmlResult deleteByPrimaryKey(String ids) {
        for (String id : ids.split(",")) {
            SysApprovalConfigRelExample example = new SysApprovalConfigRelExample();
            example.createCriteria().andAppconfigidEqualTo(Long.parseLong(id));
            if (relMapper.deleteByExample(example) == 0) {
                return HtmlResult.failure("删除失败！");
            }
            if (configMapper.deleteByPrimaryKey(Long.parseLong(id)) == 0) {
                return HtmlResult.failure("删除失败！");
            }
        }
        return HtmlResult.success("删除成功！");
    }

    @Override
    public HtmlResult insertSelective(SysApprovalConfigDto dto) throws InvocationTargetException, IllegalAccessException {
        //判断数据唯一性(提交角色，审批数据 唯一索引)
        SysApprovalConfigExample example = new SysApprovalConfigExample();
        SysApprovalConfigExample.Criteria criteria = example.createCriteria();
        criteria.andDatacodeEqualTo(dto.getDatacode());
        if (dto.getLinenumber() != null) {
            criteria.andLinenumberEqualTo(dto.getLinenumber());
        } else {
            criteria.andLinenumberEqualTo(Long.parseLong("0"));
        }
        List<SysApprovalConfig> configs = configMapper.selectByExample(example);
        if (!configs.isEmpty()) {
            return HtmlResult.failure("【" + dto.getLineuser() + "】角色已有【" + dto.getDataname() + "】审批数据的流程，无需再配置");
        }
        // 获取当前登录用户信息
        User userInfo = (User) SecurityUtils.getSubject().getSession().getAttribute(Constants.SESSION_USER_INFO);
        SysApprovalConfig config = new SysApprovalConfig();
        ConvertUtils.register(new DateConverter(null), java.util.Date.class);
        BeanUtils.copyProperties(config, dto);

        config.setCreateuserid(userInfo.getId());
        config.setCreateuser(userInfo.getUsername());
        config.setInputtime(new Date());
        int add = configMapper.insertSelective(config);
        if (add == 0) {
            return HtmlResult.failure("添加失败");
        }
        List<SysApprovalConfigRel> rels = dto.getRels();
        //TODO为结果排序
        rels = sortRels(rels);
        for (int i = 0; i < rels.size(); i++) {
            rels.get(i).setAppconfigid(config.getId());
            if (i == rels.size() - 1) {
                rels.get(i).setIslast(BaseEntity.APPROVAL_CONFIG_IS_LAST);
            } else {
                rels.get(i).setIslast(BaseEntity.APPROVAL_CONFIG_IS_NOT_LAST);
            }
            if (relMapper.insertSelective(rels.get(i)) == 0) {
                return HtmlResult.failure("添加失败");
            }
        }
        return HtmlResult.success("添加成功");
    }

    @Override
    public HtmlResult selectByExample(HttpServletRequest request) {
        return null;
    }

    @Override
    public HtmlResult selectByExample(SysApprovalConfigSeach seach) {
        Map<String, Object> map = new HashMap<>();
        if (!Strings.isNullOrEmpty(seach.getDatacode())) {
            map.put("dataCode", seach.getDatacode());
        }
        if (seach.getSubmitterRole() != null) {
            map.put("submitTerRole", seach.getSubmitterRole());
        }
        if (seach.getApprovalRole() != null) {
            map.put("approvalRole", seach.getApprovalRole());
        }
        if (!Strings.isNullOrEmpty(seach.getInputtimebegin())) {
            map.put("inputTimeBegin", seach.getInputtimebegin());
        }
        if (!Strings.isNullOrEmpty(seach.getInputtimeend())) {
            map.put("inputTimeEnd", seach.getInputtimeend());
        }
        if (!Strings.isNullOrEmpty(seach.getLastupdatetimebegin())) {
            map.put("lastUpdateTimeBegin", seach.getLastupdatetimebegin());
        }
        if (!Strings.isNullOrEmpty(seach.getLastupdatetimeend())) {
            map.put("lastUpdateTimeEnd", seach.getLastupdatetimeend());
        }
        List<SysApprovalConfigDto> dtos = configMapper.findByMapAndPage(map);
        int start = seach.getPageNum() * seach.getPageSize();
        int end = (seach.getPageNum() + 1) * seach.getPageSize();
        List<SysApprovalConfigDto> dtoss = new ArrayList<>();
        for (int i = start; i < end && i < dtos.size(); i++) {
            dtoss.add(dtos.get(i));
        }
        for (SysApprovalConfigDto dto : dtoss) {
            List<SysApprovalConfigRel> rels =  sortRels(dto.getRels());
            dto.setRels(null);
            dto.setRels(rels);
        }
        return HtmlResult.success(dtoss, dtos.size());
    }

    /**
     * 排序 -
     * @param rels -
     * @return -
     */
    private List<SysApprovalConfigRel> sortRels(List<SysApprovalConfigRel> rels) {
        //TODO为结果排序
        Collections.sort(rels, new Comparator<SysApprovalConfigRel>() {
            /*
             * int compare(Student o1, Student o2) 返回一个基本类型的整型，
             * 返回负数表示：o1 小于o2，
             * 返回0 表示：o1和o2相等，
             * 返回正数表示：o1大于o2。
             */
            public int compare(SysApprovalConfigRel o1, SysApprovalConfigRel o2) {
                //按照Start进行升序排列
                if (o1.getNumber() > o2.getNumber()) {
                    return 1;
                }
                if (o1.getNumber().equals(o2.getNumber())) {
                    return 0;
                }
                return -1;
            }
        });
        return rels;
    }

    @Override
    public HtmlResult selectByPrimaryKey(Long id) {
        return null;
    }

    @Override
    public HtmlResult updateByPrimaryKey(SysApprovalConfigDto dto) throws InvocationTargetException, IllegalAccessException {
        // 获取当前登录用户信息
        User userInfo = (User) SecurityUtils.getSubject().getSession().getAttribute(Constants.SESSION_USER_INFO);
        SysApprovalConfig config = new SysApprovalConfig();
        ConvertUtils.register(new DateConverter(null), java.util.Date.class);
        BeanUtils.copyProperties(config, dto);
        config.setLastupdateuser(userInfo.getId());
        config.setLastupdatetime(new Date());
        int update = configMapper.updateByPrimaryKeySelective(config);
        if (update == 0) {
            return HtmlResult.failure("修改失败");
        }
        SysApprovalConfigRelExample example = new SysApprovalConfigRelExample();
        example.createCriteria().andAppconfigidEqualTo(config.getId());
        if (relMapper.deleteByExample(example) == 0) {
            return HtmlResult.failure("修改失败");
        }
        List<SysApprovalConfigRel> rels = dto.getRels();
        //TODO为结果排序
        rels = sortRels(rels);
        for (int i = 0; i < rels.size(); i++) {
            rels.get(i).setAppconfigid(config.getId());
            if (i == rels.size() - 1) {
                rels.get(i).setIslast(BaseEntity.APPROVAL_CONFIG_IS_LAST);
            } else {
                rels.get(i).setIslast(BaseEntity.APPROVAL_CONFIG_IS_NOT_LAST);
            }
            if (relMapper.insertSelective(rels.get(i)) == 0) {
                return HtmlResult.failure("修改失败");
            }
        }
        return HtmlResult.success("修改成功");
    }
}
